package com.example.bes.springboot.web.war;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HttpMethodFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化方法，通常留空
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 将ServletRequest和ServletResponse转换为HttpServletRequest和HttpServletResponse
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 检查请求的方法是否为TRACE或OPTIONS
        String httpMethod = request.getMethod();
        if ("TRACE".equalsIgnoreCase(httpMethod) || "OPTIONS".equalsIgnoreCase(httpMethod)) {
            // 如果是TRACE或OPTIONS方法，返回HTTP状态码405 - Method Not Allowed
            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            response.getWriter().write("TRACE and OPTIONS methods are not allowed.");
            return;
        }

        // 继续传递请求
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 销毁方法，通常留空
    }
}
